//The purpose of dynamic_cast is to deal with the case in which
//the correctness of the conversion cannot be determined by the compiler

//dynamic cast of pointer
//For a pointer p, dynamic_cast<T*>(p) can be seen as the question:
//"Is the object pointed to by p of type T?"
 
#include <iostream>
#include <typeinfo>
using namespace std;

class A {
  int aa;
public:
  virtual int get(){cout<<"A::aa"<<endl;return aa;}
};

class B : public A{
  int bb;
public:
  int get() {cout<<"B::bb"<<endl; return bb;}
};



int main()
{
  B b;
  B& br = b;

  A& ar = dynamic_cast<A&>(b); //up-cast
  ar.get();


  cout<<"---------------------------"<<endl;
  A a;
  A& ar2 = a;
  ar2.get();
  try {
    b = dynamic_cast<B&>(ar2); //down-cast
    cout<<"aaa"<<endl;
    br = dynamic_cast<B&>(ar2);
  }
  catch(bad_cast& e) {
    cout<<"A is not a type of B"<<endl;
    cout<<e.what()<<endl;
  }

  return 0;
}
